package zkdemo;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.junit.Before;
import org.junit.Test;

public class Curator_NodeCache {
	CuratorFramework client;
	
	@Before
	public void init() {
		client = CuratorFrameworkFactory.builder()
				.connectString("192.168.10.188:2181")
				.sessionTimeoutMs(5000)
				.connectionTimeoutMs(3000)
				.retryPolicy(new ExponentialBackoffRetry(1000, 3))
				.namespace("zk-book")
				.build();
		client.start();
	}
	
	//事件监听
	@Test
	public void test() throws Exception {
		String path = client.create().creatingParentsIfNeeded()
			.withMode(CreateMode.EPHEMERAL)
			.forPath("/nodecache", "init".getBytes());
		
		NodeCache cache = new NodeCache(client, path);
		cache.start(true);//启动立即从zk上读取数据
		cache.getListenable().addListener(new NodeCacheListener() {
			@Override
			public void nodeChanged() throws Exception {
				System.out.println("node data update new :"+new String(cache.getCurrentData().getData()));
			}
		});
		
		client.setData().forPath(path, "update".getBytes());
		Thread.sleep(1000);
		client.delete().deletingChildrenIfNeeded().forPath(path);
		Thread.sleep(Long.MAX_VALUE);
		cache.close();
	}
	
	//
}
